﻿using GoodShop.Enum;
using GoodShop.seckill;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace GoodShop.Users
{
    public class UserService:CrudAppService<UserModel,UserDTO,Guid, PagedAndSortedResultRequestDto,CreateUpdateUsersDTO>,IUserService
    {
       
        IConfiguration _configuration;
        private IRepository<UserModel,Guid> _repository;
        public UserService(IRepository<UserModel, Guid> repository, IConfiguration configuration) : base(repository)
        { 
          _configuration = configuration;
          _repository= repository;
        }
     
        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet, Route("api/User/Login")]
        public  async Task<DataRes<dynamic>> UserLogin(string name,string pass)
        {
            
            var appUserName = _configuration.GetSection("WxConfig:appUserName").Value;//默认后台授权帐号
            var appUserPwd = _configuration.GetSection("WxConfig:appUserPwd").Value;//默认后台授权帐号密码
            var obj = await _repository.ToListAsync();

            var login = obj.Find(p => p.UserName == name && p.Password == pass);
            if ( login != null)
            {
                
                Ids4Service ids4Service = new Ids4Service(_configuration);
                string token = await ids4Service.GetIdsTokenAsync(appUserName, appUserPwd);
                if (string.IsNullOrEmpty(token))
                {
                    return new DataRes<dynamic>() { Code = DataCode.Error, Msg = "后台接口授权失败" };
                }
                var logins = new { login.UserName, login.Id };
                dynamic info = new { token = token,login = logins};
                RedisHelper redis = new RedisHelper();
                redis.Set("s123", info);
                return new DataRes<dynamic>() { Code = DataCode.Success, Info = info, Msg = "登陆成功" };
            }
            else
            {
                return new DataRes<dynamic>() { Code = DataCode.Onknow, Msg = "后台接口授权失败" };
            }
        }
    }
}
